// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import HeadGroup from "./headGroup";
import {Utils} from "./utils";
import {messageCenter} from "./wx/MessageCenter";

const {ccclass, property} = cc._decorator;

declare const wx: any;
declare const window: any;
@ccclass
export default class GameScene extends cc.Component {

  private headGroup: cc.Node;
  private headScript: HeadGroup;
  private myFriendsData: Array<{ KVDataList: Array<{ key: string, value: string }>, avatarUrl: string, nickname: string, spriteFrame: cc.SpriteFrame }> = [];
  private compareIndex = 0;

  onLoad() {
    this.headGroup = this.node.getChildByName('headGroup');
    this.headScript = this.headGroup.getComponent(HeadGroup);
  }

  async start() {
    this.compareIndex = 0;
    messageCenter.on('score', this.onGetScore.bind(this));
    await this.initFriendsScore();
  }

  onDestroy() {
    messageCenter.offAll();
  }

  async initFriendsScore() {
    this.myFriendsData = await Utils.getScoreInfo();
    this.myFriendsData.forEach(value => {
      let image = wx.createImage();
      image.onload = function () {
        let texture = new cc.Texture2D();
        texture.initWithElement(image);
        texture.handleLoadedTexture();
        value.spriteFrame = new cc.SpriteFrame(texture);
      };
      image.src = value.avatarUrl;
    });
  }

  private scoreIndex = 0;

  onGetScore(data) {
    const score = data.score;
    this.scoreIndex++;
    if (this.myFriendsData[this.compareIndex] !== undefined) {
      const upScore = this.myFriendsData[this.compareIndex].KVDataList[0].value;
      if (score > parseInt(upScore)) {
        const name = this.myFriendsData[this.compareIndex].nickname;
        const spriteFrame = this.myFriendsData[this.compareIndex].spriteFrame;
        this.headScript.show(name, parseInt(upScore), spriteFrame);
        this.compareIndex++;
      }
    }
  }
}
